package com.javaweb.servlet.user;

import com.javaweb.pojo.User;
import com.javaweb.service.user.UserService;
import com.javaweb.service.user.UserServiceimpl;
import com.javaweb.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    //servlet调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("进入了LoginServlet");
        //获取前端用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //和数据库中的密码对比,调用业务层代码
        UserService userService = new UserServiceimpl();
        User user = userService.login(userCode, userPassword);

        if (user!=null) //找到此人，可以登录
        {
            //将用户信息放入session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //登录成功跳转到主页
            resp.sendRedirect("jsp/frame.jsp");

        }else   //查无此人，转发到登录页面，顺带提示用户名或密码错误
        {
            req.setAttribute("error","用户名或密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
